//
//  KeFuViewController.m
//  MyNewProject
//
//  Created by sun on 2019/3/4.
//  Copyright © 2019 sun. All rights reserved.
//

#import "KeFuViewController.h"
#import "KefuTableViewCell.h"

#pragma mark -- mark 数据相关
#import "KefuModel.h"

@interface KeFuViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate> {
    NSArray <KefuInfoModel *>*_remoteData;
    KefuContentViewModel *_contentModel; //  所有问题model
    
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *textFieldView;
@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) NSMutableArray <KefuContentViewModel *>*dataArray;
@end
static NSString *const identifier = @"kefu_cell_identifier";
@implementation KeFuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gk_navTitle = @"客服";
    self.view.backgroundColor = SKColorWithHex(0xE1E1E1);
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"转人工客服" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.titleLabel.font = SKFONT_SIZE(13);
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.gk_navRightBarButtonItem = item;
    [self setupContentView];
    [self addObservers];
    [self requestKufuData];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.textField becomeFirstResponder];
}
- (void)setupContentView {
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(SKTopBar_Height);
        make.bottom.mas_equalTo(self.textFieldView.mas_top);
    }];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(10, 15, 10, 15));
    }];
    [self.textFieldView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(-SKBottomSafe_Height);
        make.height.mas_equalTo(self.view.mas_width).multipliedBy(60.0/375);
    }];
}

- (void)addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -- mark keyboard frame 监听
- (void)keyboardWillAppear:(NSNotification *)noti {
    //获取键盘高度
    NSDictionary *dict = [noti userInfo];
    NSValue *value = [dict objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardrect = [value CGRectValue];
    CGFloat bottom = -keyboardrect.size.height;
    [self.textFieldView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(bottom);
    }];
    [UIView animateWithDuration:0.5 animations:^{
        [self.textFieldView layoutIfNeeded];
    }];
    if (self.dataArray.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.dataArray.count - 1] atScrollPosition:UITableViewScrollPositionTop animated:true];
    }
}
- (void)keyboardWillHidden:(NSNotification *)noti {
    [self.textFieldView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    [UIView animateWithDuration:0.5 animations:^{
        [self.textFieldView layoutIfNeeded];
    }];
    if (self.dataArray.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.dataArray.count - 1] atScrollPosition:UITableViewScrollPositionTop animated:true];
    }
}


#pragma mark -- mark 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.showsVerticalScrollIndicator = false;
        _tableView.showsHorizontalScrollIndicator = false;
        _tableView.backgroundColor = self.view.backgroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        _tableView.tableHeaderView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 100.0;
        [_tableView registerClass:[KefuTableViewCell class] forCellReuseIdentifier:identifier];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UIView *)textFieldView {
    if (!_textFieldView) {
        _textFieldView = [[UIView alloc] init];
        _textFieldView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_textFieldView];
    }
    return _textFieldView;
}

- (UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.tintColor = [UIColor blackColor];
        _textField.borderStyle = UITextBorderStyleRoundedRect;
        _textField.font = SKFONT_SIZE(15);
        _textField.textColor = SKColorWithHex(0x333333);
        _textField.returnKeyType = UIReturnKeySend;
        _textField.delegate = self;
        [self.textFieldView addSubview:_textField];
    }
    return _textField;
}

#pragma mark -- mark UITableViewDelegate UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KefuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    KefuContentViewModel *model = self.dataArray[indexPath.section];
    SKWeakSelf;
    [cell refreshWithModel:model LinkSelected:^(NSString * _Nonnull content) {
        [weakSelf sendQuestionWith:content];
    }];
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    KefuContentViewModel *model = self.dataArray[section];
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, self.tableView.width, 30.0);
    UILabel *label = [[UILabel alloc] init];
    label.center = view.center;
    label.bounds = CGRectMake(0, 0, 130, 20);
    label.text = model.date ? model.date : @" ";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = SKFONT_SIZE(11);
    label.textColor = [UIColor whiteColor];
    label.layer.masksToBounds = true;
    label.layer.cornerRadius = 10;
    label.backgroundColor = SKColorWithHex(0x333333);
    label.layer.opacity = 0.4;
    [view addSubview:label];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark -- mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (!(textField.text.length > 0)) {
        return false; }
    [self sendQuestionWith:textField.text];
    [self.view endEditing:true];
    textField.text = nil;
    return true;
}

#pragma mark -- mark 业务逻辑

/// 处理数据
- (void)dealWithModels:(NSArray <KefuInfoModel *>*)models {
    _remoteData = models;
//    NSInteger msgType; // 0 总问题 1 提问 2 回答
    NSMutableString *context = [NSMutableString string];
    for (KefuInfoModel *model in models) {
        [context appendFormat:@"%@. %@\n", model.num, model.title];
    }
    if (context.length > 1) {
        [context deleteCharactersInRange:NSMakeRange(context.length - 1, 1)];
    }
    KefuContentViewModel *model = [[KefuContentViewModel alloc] init];
    model.content = context;
    model.date = [NSString stringFromDate:[NSDate date]];
    model.msgType = 0;
    _contentModel = model;
    self.dataArray = [NSMutableArray arrayWithObject:model];
    [self.tableView reloadData];
}


///  发送问题内容
/// @param question 问题
- (void)sendQuestionWith:(NSString *)question {
    KefuContentViewModel *model = [[KefuContentViewModel alloc] init];
    model.content = question;
    model.date = [NSString stringFromDate:[NSDate date]];
    model.msgType = 1;
    [self.dataArray addObject:model];
    [self.tableView reloadData];
    SKWeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf receiveAnswersWithKey:question];
    });
}

///  自动接收到答案
/// @param key key
- (void)receiveAnswersWithKey:(NSString *)key {
    if (!(_remoteData && _contentModel)) {
        [self showMessage:@"客服正在赶来的路上～:)"];
        return;
    }
    if ([key containsString:@"."]) {
        key = [key componentsSeparatedByString:@"."].firstObject;
    }
    KefuContentViewModel *model = [[KefuContentViewModel alloc] init];
    model.date = [NSString stringFromDate:[NSDate date]];
    model.msgType = 2;
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(KefuInfoModel  *evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return [evaluatedObject.num isEqualToString:key];
    }];
    NSArray <KefuInfoModel *>*resultData = [_remoteData filteredArrayUsingPredicate:predicate];
    if (resultData.count > 0) {
        // 处理筛选到的数据
        NSMutableString *context = [NSMutableString string];
        for (KefuInfoModel *model in resultData) {
            [context appendFormat:@"%@. %@\n", model.num, model.answer];
        }
        if (context.length > 1) {
            [context deleteCharactersInRange:NSMakeRange(context.length - 1, 1)];
        }
        KefuContentViewModel *model = [[KefuContentViewModel alloc] init];
        model.content = context;
        model.date = [NSString stringFromDate:[NSDate date]];
        model.msgType = 2;
        [self.dataArray addObject:model];
    }else {
        [self.dataArray addObject:_contentModel];
    }
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.dataArray.count - 1] atScrollPosition:UITableViewScrollPositionTop animated:true];
}

#pragma mark -- mark 获取网络数据

///  获取网络数据
- (void)requestKufuData {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Message/helpKefu" params:@{} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        KefuModel *model = [KefuModel modelWithDictionary:response];
        if ([model isSuccess]) {
            [weakSelf dealWithModels:model.data];
        }else {
            [self showMessage:model.msg];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

#pragma mark -- mark EVENT

- (void)rightButtonClick:(UIBarButtonItem *)item {
    SKWeakSelf;
    [YQNetworking getWithUrl:@"my/getKefu" params:@{} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        WJBaseModel *model = [WJBaseModel modelWithDictionary:response];
        if ([model isSuccess]) {
            BaseViewController *vc = [[BaseViewController alloc] init];
            vc.view.backgroundColor = [UIColor whiteColor];
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.center = vc.view.center;
            imageView.bounds = CGRectMake(0, 0, SCREEN_WIDTH - 40, SCREEN_WIDTH - 40);
            [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", response[@"data"]]]];
            [vc.view addSubview:imageView];
            vc.gk_navTitle = @"人工客服";
            [weakSelf.navigationController pushViewController:vc animated:true];
        }else {
            [weakSelf showMessage:model.msg];
        }
    } failBlock:^(NSError *error) {
        
    }];
}
@end
